<template>
	<view>
		<custom-header title="发券中心" />
		<scroll-view
			:scroll-y="true" 
			scroll-with-animation
			:style="{height:'calc(100vh - 128rpx - '+statusBarHeight+'px)'}" 
			class="scroll_content_wrap">
				<view class="_wrap">
					<view class="type_wrap">
						<view class="label">选择券类型<text class="required">*</text></view>
						<view class="value">
							<view 
								class="v_list"
								:class="{'active':form.type == item.id}"
								v-for="(item,index) in typeList" 
								:key="index"
								@click="handleSelectType(item)">
									{{ item.name }}
							</view>
						</view>
					</view>
					<view class="form_wrap">
						<view class="form_item">
							<view class="label">优惠券名称<text class="required">*</text></view>
							<view class="value">
								<input 
									type="text" 
									placeholder="例：满100减50" 
									v-model="form.name" 
									@input="handleBtnBisabled">
							</view>
						</view>
						<view class="form_item">
							<view class="label">优惠券金额<text class="required">*</text></view>
							<view class="value">
								<input 
									type="digit" 
									placeholder="请输入" 
									v-model="form.price" 
									@input="handleBtnBisabled">
							</view>
						</view>
						<view class="form_item">
							<view class="label">领取时间<text class="required">*</text></view>
							<view class="value_select_time" :class="{'isHave':form.getStartTime}" @click="isShowSelectTime = true">
								<view class="start">
									<view class="icon">
										<image src="/static/common/date_icon.png" mode=""></image>
									</view>
									<view class="date">{{form.getStartTime || '开始日期'}}</view>
									<view class="right_icon">
										<image src="/static/common/right.png" mode=""></image>
									</view>
								</view>
								<view class="text"> 至 </view>
								<view class="end">
									<view class="icon">
										<image src="/static/common/date_icon.png" mode=""></image>
									</view>
									<view class="date">{{form.getEndTime || '结束日期'}}</view>
									<view class="right_icon">
										<image src="/static/common/right.png" mode=""></image>
									</view>
								</view>
							</view>
						</view>
						<view class="form_item">
							<view class="label">有效期<text class="required">*</text></view>
							<view class="value_select_time" :class="{'isHave':form.validityStartTime}" @click="isShowValiditySelectTime = true">
								<view class="start">
									<view class="icon">
										<image src="/static/common/date_icon.png" mode=""></image>
									</view>
									<view class="date">{{form.validityStartTime || '开始日期'}}</view>
									<view class="right_icon">
										<image src="/static/common/right.png" mode=""></image>
									</view>
								</view>
								<view class="text"> 至 </view>
								<view class="end">
									<view class="icon">
										<image src="/static/common/date_icon.png" mode=""></image>
									</view>
									<view class="date">{{form.validityEndTime || '结束日期'}}</view>
									<view class="right_icon">
										<image src="/static/common/right.png" mode=""></image>
									</view>
								</view>
							</view>
						</view>
						<view class="form_item" v-if="form.type === 1">
							<view class="label">门槛设置<text class="required">*</text></view>
							<view class="value">
								<input 
									type="digit" 
									placeholder="请输入" 
									v-model="form.threshold"
									@input="handleBtnBisabled">
							</view>
						</view>
						<view class="form_item">
							<view class="label">发放数量<text class="required">*</text></view>
							<view class="value">
								<input 
									type="number" 
									placeholder="请输入" 
									v-model="form.count" 
									@input="handleBtnBisabled">
							</view>
						</view>
					</view>
					<view class="form_wrap">
						<view class="form_item">
							<view class="label">目标群体</view>
							<view class="value">
								全体用户
							</view>
						</view>
						<view class="form_item">
							<view class="label">发放渠道</view>
							<view class="value">
								小程序发送
							</view>
						</view>
					</view>
				</view>
		</scroll-view>
		<view class="footer_btn_wrap">
			<view class="btn_wrap">
				<button
					size="default" 
					type="default" 
					class="btn confirm" 
					:class="{'btn_disable':btnBisabled}"
					hover-class="confirm_hover" 
					:hover-stay-time="200" 
					@click="handleConfirm"
					:disabled="btnLoading || btnBisabled"
					:loading="btnLoading">立即发布</button>
			</view>
		</view>
		<!-- 自定义消息弹出层 -->
		<custom-popup
			:show="isShowToast" 
			:config="popupConfig"
			@confirm="handleMsgConfirm">
		</custom-popup>
		<!-- 领取时间 选择日期 -->
		<up-calendar 
			:show="isShowSelectTime" 
			mode="range" 
			@close="isShowSelectTime = false"
			@confirm="handleConfirmSelectTime"
			color="#F5564D"></up-calendar>
		<!-- 有效期 选择日期 -->
		<up-calendar 
			:show="isShowValiditySelectTime" 
			@close="isShowValiditySelectTime = false"
			mode="range" 
			@confirm="handleConfirmValiditySelectTime"
			color="#F5564D"></up-calendar>
	</view>
</template>

<script setup>
	import { computed, ref, onMounted } from 'vue'
	import { useStore } from 'vuex';
	import otherApi from '@/api/other'

	const store = useStore()
	
	const statusBarHeight = computed(()=>{
		return store.getters.statusBarHeight
	})
	
	// 消息弹出层
	const isShowToast = ref(false)
	const popupConfig = ref({})
	const handleMsgConfirm = (data)=>{
		isShowToast.value = false
	}
	
	const form = ref({ type:1 })
	
	// 券类型
	const typeList = ref([
		{ id:1,name:'满减券' },
		{ id:2,name:'抵用券' }
	])
	const handleSelectType = (item)=>{
		form.value.type = item.id
	}
	
	// 领取时间选择
	const isShowSelectTime = ref(false)
	const handleConfirmSelectTime = (e)=>{
		form.value.getStartTime = e[0]
		form.value.getEndTime = e[e.length - 1]
		isShowSelectTime.value = false
		handleBtnBisabled()
	}
	// 有效期时间选择
	const isShowValiditySelectTime = ref(false)
	const handleConfirmValiditySelectTime = (e)=>{
		form.value.validityStartTime = e[0]
		form.value.validityEndTime = e[e.length - 1]
		isShowValiditySelectTime.value = false
		handleBtnBisabled()
	}
	
	
	// 判断是否可点击按钮
	const btnBisabled = ref(true)
	const handleBtnBisabled = ()=>{
		console.log(form.value)
		if(!form.value.name){
			return btnBisabled.value = true;
		}
		if(!form.value.price){
			return btnBisabled.value = true;
		}
		if(!form.value.getStartTime){
			return btnBisabled.value = true;
		}
		if(!form.value.validityStartTime){
			return btnBisabled.value = true;
		}
		if(form.value.type === 1 && !form.value.threshold){
			return btnBisabled.value = true;
		}
		if(!form.value.count){
			return btnBisabled.value = true;
		}
		btnBisabled.value = false
	}
	
	const validateForm = () => {
		if (!form.value.name.trim()) {
			popupConfig.value = { message: '请输入优惠券名称' }
			isShowToast.value = true
			return false
		}

		if (!form.value.price) {
			popupConfig.value = { message: '请输入优惠券金额' }
			isShowToast.value = true
			return false
		}

		if (!form.value.getStartTime) {
			popupConfig.value = { message: '请选择领取时间' }
			isShowToast.value = true
			return false
		}

		if (!form.value.validityStartTime) {
			popupConfig.value = { message: '请选择有效期' }
			isShowToast.value = true
			return false
		}

		if (form.value.type === 1 && !form.value.threshold) {
			popupConfig.value = { message: '请输入门槛设置' }
			isShowToast.value = true
			return false
		}

		if (!form.value.count) {
			popupConfig.value = { message: '请输入发放数量' }
			isShowToast.value = true
			return false
		}

		return true
	}

	// 确认
	const btnLoading = ref(false)
	const handleConfirm = async () => {
		if(!validateForm())return
		if (btnLoading.value) {
			return
		}

		try {
			btnLoading.value = true

			// 3. 构造优惠券数据
			const couponData = {
				couponName: form.value.name.trim(),
				discountValue: Number(form.value.price),
				startDate: form.value.getStartTime,
				endDate: form.value.getEndTime,
				effectiveDate: form.value.validityStartTime,
				expireDate: form.value.validityEndTime,
				totalLimit: Number(form.value.count),
			}

			let result
			if (form.value.type === 1) {
				// 满减券
				couponData.minOrderAmount = Number(form.value.threshold)
				result = await otherApi.addThresholdCoupon(couponData)
			} else if (form.value.type === 2) {
				result = await otherApi.addCoupon(couponData)
			} else {
				throw new Error('未知的优惠券类型')
			}

			uni.navigateTo({
				url: `/pages/couponSuccess/couponSuccess?id=${result.id || '123'}`
			})

		} catch (error) {
			console.error('优惠券创建失败:', error)
			uni.showToast({
				title: error.message || '优惠券创建失败，请重试',
				icon: 'none'
			})

		} finally {
			btnLoading.value = false
		}
	}
</script>

<style lang="scss">
	._wrap{
		padding:0 20rpx;
		.label{
			font-size: 28rpx;
			color: #333333;
			.required{
				color: #F70707;
			}
		}
		.type_wrap{
			border-radius: 20rpx;
			background: #FFFFFF;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 25rpx;
			margin-top: 20rpx;
			.value{
				display: flex;
				.v_list{
					width: 160rpx;
					height: 60rpx;
					line-height: 60rpx;
					text-align: center;
					border-radius: 8rpx;
					background: #fff;
					border: 1px solid #999999;
					font-size: 24rpx;
					color: #999999;
					margin-left: 20rpx;
					&.active{
						background: #FCEEF0;
						border: 1px solid #F5564D;
						color: #F5564D;
					}
				}
			}
		}
		.form_wrap{
			border-radius: 20rpx;
			background: #FFFFFF;
			margin-top: 20rpx;
			padding: 0 25rpx;
			.form_item{
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 25rpx 0;
				border-top: 1px solid #F0F0F0;
				&:first-child{
					border: 0;
				}
				.value_select_time{
					display: flex;
					align-items: center;
					color: #999;
					font-size: 24rpx;
					.start,.end{
						display: flex;
						align-items: center;
						.icon{
							width: 28rpx;
							height: 27rpx;
							display: flex;
						}
						.date{
							padding: 0 10rpx;
						}
						.right_icon{
							width: 10rpx;
							height: 20rpx;
							display: flex;
						}
					}
					.text{
						padding: 0 20rpx;
					}
					&.isHave{
						color: #666;
					}
				}
				.value{
					color: #666;
					font-size: 24rpx;
				}
			}
		}
	}
	.input-placeholder{
		font-size: 24rpx;
		color: #999;
		text-align: right;
	}
	input {
		font-size:24rpx;
		color: #666;
		text-align: right;
	}
</style>
